extends Node2D

var storyAPI = preload("res://scene/play/storyAPI.gd").new()
var storyItem = preload('res://scene/play/storyItem.gd')
var storyStack = []
var layer = null

func _ready():
	Model.play = self
	layer = $layer
	$button.set_size(OS.window_size)
	#get_node("Sprite").set_self_modulate(Color(1, 1, 1, 0.1))
	pass # Replace with function body.

func _process(delta):
	if storyStack.empty():
		return
	if Model.select.working():
		# 分支选择中,暂停脚本执行
		return
	if Model.dialog.isSpeaking():
		# 对白显示中,暂停脚本执行
		return
	var item = storyStack.back()
	item.update(delta)
	if item.isPause():
		return
	if item.isEnd():
		storyStack.pop_back()
		item.queue_free()
	else:
		if item.currCodeIsNotTag():
			var code = item.currCode()
			storyAPI.parse(code, {
				"fileName": item.name(),
				"lineNum": item.index()
			})
		item.nextStep()
	pass

func addStory(fileName : String):
	var item = storyItem.new()
	if !item.loadConfig(fileName):
		item.queue_free()
		return
	storyStack.append(item)
	
func popStory():
	if storyStack.empty():
		return
	var item = storyStack.back()
	storyStack.pop_back()
	item.queue_free()

func pauseStory(ms : int):
	if storyStack.empty():
		return
	var item = storyStack.back()
	item.pause(ms)

func seekStory(tag : String):
	if storyStack.empty():
		return
	var item = storyStack.back()
	item.seekTag(tag)
	
func clearStory():
	while !storyStack.empty():
		popStory()
	storyAPI.allclear()

func _on_button_pressed():
	var dialog = Model.dialog
	dialog.click()

func getSaveData():
	var r = {
		"story": []
	}
	for i in range(storyStack.size()):
		var item = storyStack[i]
		r.story.append(item.getSaveData())
	return r
	
func setSaveData(data : Dictionary):
	while !storyStack.empty():
		popStory()
	var story = data.story
	for i in range(story.size()):
		var item = storyItem.new()
		storyStack.append(item)
		item.setSaveData(story[i])
	pass
